﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GoPlay.Models;

namespace GoPlay.Controllers
{
    [Authorize]
    public class TeamsController : Controller
    {
        IRepository<Team> _repository;

        public TeamsController() : this(new EFRepository<Team>()) { }

        public TeamsController(IRepository<Team> repository)
        {
            _repository = repository;
        }


        //
        // GET: /Teams/

        public ActionResult Index()
        {
            var results = _repository.GetAllByUserId(Convert.ToInt32(Session["UserId"]));
            ViewBag.Teams = results;
            return View(results);
        }

        //
        // GET: /Teams/Details/5

        public ActionResult Details(int id = 0)
        {
            string[] s = { "Games", "Players" };
            Team team = _repository.GetByID(id, s);
            return View(team);
        }

        //
        // GET: /Teams/Create

        public ActionResult Create()
        {
            var Team = new Team();
            return View(Team);
        }

        //
        // POST: /Teams/Create

        [HttpPost]
        public ActionResult Create(Team team)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _repository.Insert(team);
                    _repository.SaveChanges();
                    Session["FlashSuccess"] = "Your Team was created.";
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex);
                Session["FlashError"] = ex.Message;
            }

            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    Session["FlashError"] += error.ErrorMessage;
                }
            }
            return View(team);
        }

        //
        // GET: /Teams/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Team c = _repository.GetByID(id);
            if (c == null)
            {
                return HttpNotFound();
            }
            return View(c);
        }

        //
        // POST: /Teams/Edit/5

        [HttpPost]
        public ActionResult Edit(Team team)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    _repository.Update(team);
                    _repository.SaveChanges();
                    Session["FlashSuccess"] = "Your Team was updated.";
                    return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex);
                Session["FlashError"] = ex.Message;
            }

            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    Session["FlashError"] += error.ErrorMessage;
                }
            }
            return View(team);
        }

        //
        // GET: /Teams/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Team c = _repository.GetByID(id);
            if (c == null)
            {
                return HttpNotFound();
            }
            return View(c);
        }

        //
        // POST: /Teams/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {

            try
            {
                string[] s = { "Games", "Players" };
                Team team = _repository.GetByID(id, s);
                
                // --- BEGIN HACK ---
                // Due to EF 5.0 bug, we have to *manually* delete all children first. This is to avoid the EF bug that reads:
                //      Introducing FOREIGN KEY constraint 'FK_dbo.Games_dbo.Teams_TeamID' on table 'Games' may cause cycles or multiple cascade paths. 
                //      Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
                //      Could not create constraint. See previous errors.
                foreach (var g in team.Games.ToList())
                {
                    team.Games.Remove(g);
                }
                foreach (var p in team.Players.ToList())
                {
                    team.Players.Remove(p);
                }
                // --- END HACK ---

                _repository.Delete(team);
                _repository.SaveChanges();
                Session["FlashSuccess"] = "Your Team was deleted.";
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex);
                Session["FlashError"] = ex.Message;
            }

            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
                foreach (ModelError error in modelState.Errors)
                {
                    Session["FlashError"] += error.ErrorMessage;
                }
            }
            return View();
        }
    }
}
